<template>
  <div class="login-container">
    <div class="login-card">
      <div class="login-header">
        <h2>手机验证码登录</h2>
        <p class="subtitle">欢迎回来</p>
      </div>

      <form class="login-form" @submit.prevent="handleLogin">
        <div class="form-group">
          <label>手机号</label>
          <div class="input-wrapper">
            <el-icon><Iphone /></el-icon>
            <input 
              type="tel" 
              v-model="phone" 
              placeholder="请输入手机号"
              maxlength="11"
              required
            />
          </div>
        </div>

        <div class="form-group">
          <label>图形验证码</label>
          <div class="input-wrapper captcha-wrapper">
            <el-icon><Picture /></el-icon>
            <input 
              type="text" 
              v-model="captcha"
              placeholder="请输入图形验证码"
              maxlength="4"
              required
            />
            <img 
              :src="captchaUrl" 
              alt="验证码" 
              class="captcha-img"
              @click="refreshCaptcha"
              v-if="captchaUrl"
            />
          </div>
        </div>

        <div class="form-group">
          <label>验证码</label>
          <div class="input-wrapper verification-code">
            <el-icon><Watermelon /></el-icon>
            <input 
              type="text" 
              v-model="code"
              placeholder="请输入验证码"
              maxlength="6"
              required
            />
            <button 
              type="button" 
              class="send-code-btn" 
              :disabled="countdown > 0" 
              @click="sendCode"
            >
              {{ countdown > 0 ? `${countdown}秒后重试` : '发送验证码' }}
            </button>
          </div>
          <!-- 验证码显示区域 -->
          <div v-if="receivedCode" class="code-hint">
            <span class="code-text">验证码：{{ receivedCode }}</span>
          </div>
        </div>

        <button type="submit" class="login-btn">
          登录
        </button>

        <div class="register-link">
          还没有账号？<a href="#" @click.prevent="$router.push('/register')">立即注册</a>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup>
import { ref, onBeforeUnmount, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getCode, login, getCaptchaImage } from '@/axios/auth'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { Iphone, Watermelon, Picture } from '@element-plus/icons-vue'
import axios from '@/axios/index'

const phone = ref('');
const code = ref('');
const captcha = ref('');
const captchaUrl = ref('');
const countdown = ref(0);
const receivedCode = ref('');
let countdownTimer = null;
const router = useRouter();
const userStore = useUserStore();

// 刷新验证码
const refreshCaptcha = async () => {
  try {
    // 释放旧的URL对象
    if (captchaUrl.value) {
      URL.revokeObjectURL(captchaUrl.value);
      captchaUrl.value = '';
    }
    
    const response = await getCaptchaImage();
    console.log('验证码响应类型:', response.type);
    console.log('验证码响应大小:', response.size);
    
    if (response instanceof Blob && response.size > 0 && response.type === 'image/jpeg') {
      captchaUrl.value = URL.createObjectURL(response);
      console.log('验证码URL创建成功:', captchaUrl.value);
    } else {
      console.error('验证码响应格式错误或为空:', {
        isBlob: response instanceof Blob,
        size: response.size,
        type: response.type
      });
      ElMessage.error('验证码获取失败，请点击刷新');
    }
  } catch (error) {
    console.error('获取验证码失败:', error);
    ElMessage.error('验证码获取失败，请点击刷新');
  }
};

// 组件挂载时获取验证码
onMounted(() => {
  refreshCaptcha();
});

// 组件卸载时清理
onBeforeUnmount(() => {
  if (countdownTimer) {
    clearInterval(countdownTimer);
  }
  // 释放URL对象
  if (captchaUrl.value) {
    URL.revokeObjectURL(captchaUrl.value);
  }
});

// 发送验证码
const sendCode = async () => {
  if (!phone.value) {
    ElMessage.error('请输入手机号');
    return;
  }
  if (!/^1[3-9]\d{9}$/.test(phone.value)) {
    ElMessage.error('请输入正确的手机号');
    return;
  }
  if (!captcha.value) {
    ElMessage.error('请输入图形验证码');
    return;
  }

  try {
    // 开始倒计时
    countdown.value = 60;
    countdownTimer = setInterval(() => {
      countdown.value--;
      if (countdown.value <= 0) {
        clearInterval(countdownTimer);
      }
    }, 1000);

    // 请求后端发送验证码
    const res = await getCode(phone.value);
    if (res.code === 1 && res.data && res.data.code) {
      receivedCode.value = res.data.code;
      code.value = res.data.code; // 自动填充到输入框
      ElMessage.success('验证码已发送，请注意查收');
    } else {
      ElMessage.error(res.msg || '验证码发送失败');
      clearInterval(countdownTimer);
      countdown.value = 0;
    }
  } catch (error) {
    ElMessage.error(error.message || '验证码发送失败');
    clearInterval(countdownTimer);
    countdown.value = 0;
  }
};

// 登录功能
const handleLogin = async () => {
  if (!phone.value || !code.value || !captcha.value) {
    ElMessage.error('请填写完整信息');
    return;
  }
  try {
    const res = await login({ 
      phone: phone.value, 
      code: code.value,
      captcha: captcha.value 
    });
    if (res.code === 1 && res.data) {
      // 保存 JWT token 到 pinia 和 localStorage
      userStore.setToken(res.data)
      ElMessage.success('登录成功');
      // 跳转到用户页
      router.push('/user')
    } else {
      ElMessage.error(res.msg || '登录失败');
      // 登录失败时刷新验证码
      refreshCaptcha();
    }
  } catch (error) {
    ElMessage.error(error.message || '登录失败');
    // 登录失败时刷新验证码
    refreshCaptcha();
  }
};
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  background: #f8f9fa;
}

.login-card {
  width: 100%;
  max-width: 480px;
  background: white;
  border-radius: 12px;
  padding: 40px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.login-header {
  text-align: center;
  margin-bottom: 40px;
}

.login-header h2 {
  font-size: 28px;
  color: #2c3e50;
  margin: 0 0 10px 0;
}

.subtitle {
  color: #666;
  margin: 0;
}

.login-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-group label {
  color: #2c3e50;
  font-size: 14px;
}

.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

.input-wrapper i {
  position: absolute;
  left: 12px;
  color: #666;
}

.input-wrapper input {
  width: 100%;
  padding: 12px 12px 12px 40px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 16px;
  transition: all 0.3s;
}

.input-wrapper input:focus {
  border-color: #4CAF50;
  outline: none;
  box-shadow: 0 0 0 2px rgba(76, 175, 80, 0.1);
}

.input-wrapper i:last-child {
  left: auto;
  right: 12px;
  cursor: pointer;
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: -10px;
}

.remember-me {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #666;
  font-size: 14px;
  cursor: pointer;
}

.remember-me input[type="checkbox"] {
  width: 16px;
  height: 16px;
  margin: 0;
}

.forgot-password {
  color: #4CAF50;
  text-decoration: none;
  font-size: 14px;
}

.forgot-password:hover {
  text-decoration: underline;
}

.login-btn {
  background: #4CAF50;
  color: white;
  border: none;
  padding: 14px;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s;
  margin-top: 10px;
}

.login-btn:hover {
  background: #45a049;
  transform: translateY(-2px);
}

.register-link {
  text-align: center;
  margin-top: 20px;
  color: #666;
}

.register-link a {
  color: #4CAF50;
  text-decoration: none;
  font-weight: 500;
}

.register-link a:hover {
  text-decoration: underline;
}

@media (max-width: 480px) {
  .login-card {
    padding: 30px 20px;
  }
}

.verification-code {
  display: flex;
  gap: 10px;
}

.verification-code input {
  flex: 1;
}

.send-code-btn {
  white-space: nowrap;
  padding: 0 15px;
  height: 44px;
  background: #4CAF50;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.send-code-btn:hover:not(:disabled) {
  background: #45a049;
}

.send-code-btn:disabled {
  background: #cccccc;
  cursor: not-allowed;
}

.input-wrapper input {
  height: 44px;
}

.code-hint {
  margin-top: 8px;
  padding: 8px 12px;
  background: #f0f9eb;
  border-radius: 4px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.code-text {
  color: #67c23a;
  font-weight: bold;
  font-size: 14px;
}

.captcha-wrapper {
  display: flex;
  gap: 10px;
}

.captcha-wrapper input {
  flex: 1;
}

.captcha-img {
  height: 44px;
  border-radius: 6px;
  cursor: pointer;
  transition: opacity 0.3s;
  border: 1px solid #ddd;
}

.captcha-img:hover {
  opacity: 0.8;
  border-color: #4CAF50;
}
</style> 